package br.usp.ime.components.daos;

import java.util.List;

import org.hibernate.Session;
import org.hibernate.Transaction;
import org.hibernate.criterion.Restrictions;

import br.com.caelum.vraptor.ioc.ApplicationScoped;
import br.com.caelum.vraptor.ioc.Component;
import br.usp.ime.entities.Task;
import br.usp.ime.entities.User;

@Component
@ApplicationScoped
public class TaskDao {

    private final Session session;

    public TaskDao(Session session) {
        this.session = session;
    }

    public boolean taskExists(Task task) {
        return loadTask(task) != null;
    }

    public void addTask(Task task) {
        Transaction tx = this.session.beginTransaction();
        this.session.save(task);
        tx.commit();
    }

    public void updateTask(Task task) {
        if (taskExists(task)) {
            Transaction tx = this.session.beginTransaction();
            this.session.merge(task);
            tx.commit();
        }
        // this.session.refresh(task);
    }

    public Task loadTask(Task task) {
        if (task == null)
            return null;
        session.clear();
        return (Task) session.createCriteria(Task.class)
                .add(Restrictions.eq("id", task.getId())).uniqueResult();
    }

    public void deleteTask(Task task) {
        Task deletedTask = loadTask(task);
        if (task != null) {
            Transaction tx = this.session.beginTransaction();
            this.session.delete(deletedTask);
            tx.commit();
        }
    }

    @SuppressWarnings("unchecked")
    public List<Task> loadTasksOwnedByUser(User user) {
        List<Task> list = (List<Task>) this.session.createCriteria(Task.class)
                .add(Restrictions.eq("taskOwner.getLogin()", user.getLogin()))
                .list();
        return list;
    }

    @SuppressWarnings("unchecked")
    public List<Task> loadTasksUserIsInChargeOf(User user) {
        List<Task> list = (List<Task>) this.session
                .createQuery(
                        "from Task as t inner join fetch t.usersInCharge as uch where uch.login = ?")
                .setString(0, user.getLogin()).list();
        return list;
    }

    @SuppressWarnings("unchecked")
    public List<Task> listAllTasks() {
        return this.session.createCriteria(Task.class).list();
    }
    
    @SuppressWarnings("unchecked")
    public List<Task> generateTasksByIds(Long ids[]) {
		List<Task> list = (List<Task>) this.session
                .createQuery("from Task where id in (:ids)")
                .setParameterList("ids", ids)
                .list();
    	return list;
    }    

}
